<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<!-- 引入 Bootstrap v3 的 CSS 文件 -->
		<link rel="stylesheet" href="bootstrap-3.4.1/css/bootstrap.css">
		<!-- 引入 jQuery（Bootstrap v3 依赖） -->
		<script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.1.1/jquery.min.js"></script>
		<!-- 引入 Bootstrap v3 的 JS 文件 -->
		<script src="bootstrap-3.4.1/js/bootstrap.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
		<title>员工管理界面</title>
		<style>
			.ytd {
				text-align: center;
			}
		</style>
	</head>
	<body>
		<nav class="navbar navbar-default">
			<div class="container-fluid">
				<!-- Brand and toggle get grouped for better mobile display -->
				<div class="navbar-header">
					<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
						data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
						<span class="sr-only">Toggle navigation</span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
						<span class="icon-bar"></span>
					</button>
					<a class="navbar-brand" href="#">员工管理</a>
				</div>

				<!-- Collect the nav links, forms, and other content for toggling -->
				<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
					<form class="navbar-form navbar-left">
						<div class="form-group">
							<input type="text" class="form-control" placeholder="员工部门">
						</div>
						<div class="form-group">
							<input type="text" class="form-control" placeholder="员工姓名">
						</div>
						<div class="form-group">
							<select class="form-control">
								<option value="-1">所有</option>
								<option value="0">启用</option>
								<option value="1">禁用</option>
							</select>
						</div>
						<button class="btn btn-default">查询</button>
					</form>
					<ul class="nav navbar-nav navbar-right">
						<li><a href="#" data-toggle="modal" data-target="#addDictModal">添加员工</a></li>
						<li class="dropdown">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
								aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
							<ul class="dropdown-menu">
								<li><a href="#">Action</a></li>
								<li><a href="#">Another action</a></li>
								<li><a href="#">Something else here</a></li>
								<li role="separator" class="divider"></li>
								<li><a href="#">Separated link</a></li>
							</ul>
						</li>
					</ul>
				</div><!-- /.navbar-collapse -->
			</div><!-- /.container-fluid -->
		</nav>
		
		<script>
			// 当浏览器加载完毕DOM以后就要自动执行获取分页数据
			window.onload = function () {
				initData(1, 10);
			}
			function initData(pn, size) {
				
				$.ajax({
					// 后端的请求地址
					url: 'http://localhost:8080/emp/' + pn + '/' + size,
					// 后端的请求方式
					type: 'get',
					// 这里不传递data参数，所以不用谢
					// data: {
						
					// }
					dataType: 'json',
					// 如果请求响应成功
					success: function (res) {
						if (res.code == 200) {
							// 获取新数据的时候把原有的数据清除掉
							$("#tb").empty();
							$("#pageBar").empty();
							
							// 拿到所有的数据集合
							let dicts_temp = res.data.list
							// 遍历字典集合
							for (var i = 0; i < dicts_temp.length; i++) {
								let emp = dicts_temp[i] // 每遍历一次都是一个单独的字典对象，对象.属性就能拿到值
								let r = emp.role
								if (r!=null) {
									$("<tr><td class='ytd'>"+emp.id+"</td><td class='ytd'>"+emp.uusername+"</td><td class='ytd'>"+r.role_name+"</td><td class='ytd'>"+"<a href='#'>"+emp.uusername+"</a>"+"</td><td class='ytd'>"+emp.uemail+"</td><td class='ytd'>"+(emp.ustatus == 0 ? '启用': '禁用')+"</td><td class='ytd'>"+emp.ucreate_time+"</td><td class='ytd'><button  data-toggle='modal' data-target='#updateDictModal' class='btn btn-xs btn-primary' onclick='updateDict("+emp.id +"," + res.data.pageNum +")'>编辑</button>&nbsp;<button class='btn btn-xs btn-info' onclick='accessPri("+emp.id+")' data-toggle='modal' data-target='#priModal'>授权</button>&nbsp;<button class='btn btn-xs btn-danger'>删除</button></td></tr>").appendTo($("#tb"));
								}
								$("<tr><td class='ytd'>"+emp.id+"</td><td class='ytd'>"+emp.uusername+"</td><td class='ytd'>暂未授权</td><td class='ytd'>"+"<a href='#'>"+emp.uusername+"</a>"+"</td><td class='ytd'>"+emp.uemail+"</td><td class='ytd'>"+(emp.ustatus == 0 ? '启用': '禁用')+"</td><td class='ytd'>"+emp.ucreate_time+"</td><td class='ytd'><button  data-toggle='modal' data-target='#updateDictModal' class='btn btn-xs btn-primary' onclick='updateDict("+emp.id +"," + res.data.pageNum +")'>编辑</button>&nbsp;<button class='btn btn-xs btn-info' onclick='accessPri("+emp.id+")' data-toggle='modal' data-target='#priModal'>授权</button>&nbsp;<button class='btn btn-xs btn-danger'>删除</button></td></tr>").appendTo($("#tb"));
							}
							
							// 输出当前页
							console.log('当前页:', res.data.pageNum)
							
							// 拼接页码
							// 首先拼接上一页
							$("<li><a href='#' aria-label='Previous' onclick='initData("+ (res.data.pageNum - 1) +"," + 10 +")'><span aria-hidden='true'>&laquo;</span></a></li>").appendTo($("#pageBar"));
							// 其次拿到总页数
							let current_pages = res.data.navigatepageNums
							for (var i = 0; i < current_pages.length; i++) {
								let page = current_pages[i]
								// 判断当前页和后端返回的页码是否相同，相同的话就给当前页添加背景
								console.log(pn,res.data.pageNum )
								if (pn == page) {
									$("<li class='active'><a href='#' onclick='initData("+page +"," + 10 +")'>"+page+"</a></li>").appendTo($("#pageBar"));
								} else {
									$("<li><a href='#' onclick='initData("+page +"," + 10 +")'>"+page+"</a></li>").appendTo($("#pageBar"));
								}
								
							}
							// 最后拼接下一页
							$("<li><a href='#' aria-label='Next' onclick='initData("+ (res.data.pageNum + 1) +"," + 10 +")'><span aria-hidden='true'>&raquo;</span></a></li>").appendTo($("#pageBar"));
						}
					},
					complete: function (err) {
						console.log('响应失败', err)
					}
				});
			}
			
			// 给员工授权
			function accessPri (eid) {
				document.getElementById("eid").value = eid
				// 接收员工的ID
				// 加载所有角色到选择角色的下拉框中
				$.ajax({
					url: 'http://localhost:8080/role/roles/1/10',
					type: 'get',
					dataType: 'json',
					success: function (res) {
						if (res.code == 200) {
							$("#selectRoles").empty()
							let objs = res.data.list
							for (var i = 0; i < objs.length; i++) {
								let ob = objs[i]
								$("<option value='"+ob.id+"'>"+ob.role_name+"</option>").appendTo($("#selectRoles"))
							}
						}
					}
				});
				
			}
			
			// 正式授权
			function priDo() {
				
				// 保存授权的结果
				// 得到员工的ID和角色的ID
				let rid = document.getElementById("selectRoles").value
				let eid = document.getElementById("eid").value
				
				// 封装一个JSON对象
				let erids = {'eid': eid, 'rid': rid}
				$.ajax({
					url: 'http://localhost:8080/pri/add',
					data: JSON.stringify(erids),
					type: 'post',
					dataType: 'json',
					contentType: 'application/json',
					success: function (res) {
						if (res.code == 200) {
							alert('给员工授权成功');
							$('#priModal').modal('hide')
							// 重新加载当前页面
							initData(1, 10);
						}
					}
				});
			}
			
			// 修改字典信息
			function updateDict (id, pn) {
				// console.log('要修改的数据是:', id)
				// 修改前获取最新的数据
				$.ajax({
					url: 'http://localhost:8080/dict/' + id,
					type: 'get',
					dataType: 'json',
					success: function (res) {
						console.log('res', res)
						// 必须是200的时候才是执行成功的
						// == && === 区别：=== 表示数值和数据类型都是相等
						if (res.code == 200) {
							// 从data中拿到最新的数据
							let obj = res.data
							document.getElementById("updateDname").value = res.data.dname
							document.getElementById("updateDtype").value = res.data.dtype
							document.getElementById("version").value = res.data.version
							document.getElementById("uid").value = id // 要修改的数据需要有个条件
							
							// 缓存当前的页码，为了更新完毕后要回到原来的页码
							localStorage.setItem("pn", pn)
						}
					},
					complete: function (err) {
						console.log('响应失败:', err)
					}
				});
			}
			
			// 更新字典信息
			function updateDictDo () {
				// 获取用户改过的数据
				let dname = document.getElementById("updateDname").value
				let dtype = document.getElementById("updateDtype").value
				// 获取两个单选框
				let dstate = document.getElementsByName("dstate_update")
				// 临时变量接受最终用户选中的字典状态
				let temp
				// 遍历所有的单选框找到用户选中的那个单选框的值
				for (var i = 0; i < dstate.length; i++) {
					if (dstate[i].checked) {
						temp = dstate[i].value
						break // 跳出循环：continue 跳出当前循环并且进入下一次循环；break 跳出循环不再执行
					}
				}
				let version = document.getElementById("version").value
				// console.log(dname +',' + temp)
				
				// 封装字典对象
				let dict_obj = {'id': document.getElementById("uid").value,'dname': dname, 'dtype': dtype, 'dstate': temp, 'version': version}
				
				// 将封装的对象传递后端
				$.ajax({
					url: 'http://localhost:8080/dict/update',
					type: 'put',
					dataType: 'json', // 把JSON对象转成JSON字符串
					contentType: 'application/json', // 前端给后端的数据的数据格式
					data: JSON.stringify(dict_obj), // 前端给后端的数据
					success: function (res) {
						console.log('响应成功:', res)
						if (res.code == 200) {
							alert('更新成功')
							// 关闭模态框
							$('#updateDictModal').modal('hide')
							// 刷新页面，回到原来的页面
							initData(localStorage.getItem("pn"), 10)
						}
					},
					complete: function (err) {
						console.log('响应失败:', err)
					}
				});
			}
		</script>
		
		<!-- 数据字典的表格 -->
		<table class="table table-bordered table-striped table-condensed">
			<thead>
				<th class='ytd'>#</th>
				<th class='ytd' style="width: 180px;">员工姓名</th>
				<th class='ytd'>员工角色</th>
				<th class='ytd'>员工账号</th>
				<th class='ytd'>员工邮箱</th>
				<th class='ytd'>员工状态</th>
				<th class='ytd'>创建时间</th>
				<th class='ytd'>操作</th>
			</thead>
			<tbody id="tb">
				
			</tbody>
			
			<tfoot>
				<tr>
					<td colspan="8" style="text-align: center;">
						<nav aria-label="Page navigation">
						  <ul class="pagination" id="pageBar">
						  </ul>
						</nav>
					</td>
				</tr>
			</tfoot>
		</table>

		<!-- 添加员工模态框 -->
		<div class="modal fade" id="addDictModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
								aria-hidden="true">&times;</span></button>
						<h4 class="modal-title" id="myModalLabel">添加员工</h4>
					</div>
					<div class="modal-body">
						<form class="form-horizontal">
							<div class="form-group">
								<label for="realname" class="col-sm-2 control-label">员工姓名</label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="realname" placeholder="请输入员工姓名">
								</div>
							</div>
							<div class="form-group">
								<label for="uusername" class="col-sm-2 control-label">员工账号</label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="uusername" placeholder="请输入员工账号">
								</div>
							</div>
							<div class="form-group">
								<label for="uemail" class="col-sm-2 control-label">员工邮箱</label>
								<div class="col-sm-10">
									<input type="email" class="form-control" id="uemail" placeholder="请输入员工邮箱">
								</div>
							</div>
							<div class="form-group">
								<label for="inputDtype" class="col-sm-2 control-label">员工状态</label>
								<div class="col-sm-10">
									<div class="checkbox">
										<label>
											<input type="radio" value="0" name="ustatus" checked> 启用
										</label>
										<label>
											<input type="radio" value="1" name="ustatus"> 禁用
										</label>
									</div>
								</div>
							</div>
							<div class="form-group">
								<div class="col-sm-offset-1 col-sm-10">
									<div class="checkbox">
										<label>
											<span style="color: red;" id="tip"></span>
										</label>
										
									</div>
								</div>
							</div>
						</form>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						<button type="button" class="btn btn-primary" onclick="saveEmp()">保存</button>
					</div>
				</div>
			</div>
		</div>
		
		<script>
			// 保存员工信息
			function saveEmp () {
				let realname = document.getElementById("uusername").value
				let uusername = document.getElementById("uusername").value
				let uemail = document.getElementById("uemail").value
				let ustatus = document.getElementsByName("ustatus")
				
				if ('' == realname || '' == uusername || '' == uemail) {
					document.getElementById("tip").innerText = "请将表单填写完整再提交……"
					return
				}
				
				let ustate;
				for (var i = 0; i < ustatus.length; i++) {
					let os = ustatus[i]
					if (os.checked) {
						ustate = os.value
					}
				}
				
				const secretKey = "VpV2UosNCVe9pfzo"; // 32字节AES密钥
				const plainText = "123456";
				const fixedIV = "0123456789abcdef"; // 16字节的固定IV，用于测试
				const encryptedData = encryptAES(plainText, secretKey, fixedIV);
				
				let obj = {
					'realname': uusername,
					'uusername':uusername,
					'upassword': encryptedData,
					'uemail': uemail,
					'ustatus': ustate
				}
				
				console.log('添加员工的信息:', obj)
				
				
				
				$.ajax({
					url: 'http://localhost:8080/emp/add',
					data: JSON.stringify(obj),
					type: 'post',
					dataType: 'json',
					contentType: 'application/json',
					success: function (res) {
						if (res.code == 200) {
							alert('员工添加成功,密码默认123456.')
							$('#addDictModal').modal('hide')
							// 刷新列表页面
							initData(1, 10);
						}
					} 
				});
			}
			
			// 测试加密
			// const secretKey = "VpV2UosNCVe9pfzo"; // 16字节密钥
			// const plainText = "123456";
			// const fixedIV = "0123456789abcdef"; // 16字节的固定IV，用于测试
			// const encryptedData = encryptAES(plainText, secretKey, fixedIV);
			// console.log("固定IV的加密结果:", encryptedData);
			
			// 加密函数
			function encryptAES(plainText, secretKey, fixedIV) {
				// 使用固定IV
				const iv = CryptoJS.enc.Utf8.parse(fixedIV); // 注意：这里固定IV必须是16字节字符串
			
				const encrypted = CryptoJS.AES.encrypt(plainText, CryptoJS.enc.Utf8.parse(secretKey), {
					iv: iv,
					mode: CryptoJS.mode.CBC,
					padding: CryptoJS.pad.Pkcs7
				});
			
				// 组合IV和密文: IV(16字节) + 密文
				const combined = iv.concat(encrypted.ciphertext);
				return combined.toString(CryptoJS.enc.Base64);
			}
		</script>
		
		
		<!-- 修改字典模态框 -->
		<div class="modal fade" id="updateDictModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
								aria-hidden="true">&times;</span></button>
						<h4 class="modal-title" id="myModalLabel">修改字典信息</h4>
					</div>
					<div class="modal-body">
						<form class="form-horizontal">
							<div class="form-group">
								<label for="updateDname" class="col-sm-2 control-label">字典名称</label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="updateDname" placeholder="请输入字典名称">
								</div>
							</div>
							<div class="form-group">
								<label for="updateDtype" class="col-sm-2 control-label">字典类型</label>
								<div class="col-sm-10">
									<input type="text" class="form-control" id="updateDtype" placeholder="请输入字典类型">
								</div>
							</div>
							<div class="form-group">
								<label for="inputDtype" class="col-sm-2 control-label">字典状态</label>
								<div class="col-sm-10">
									<div class="checkbox">
										<label>
											<input type="radio" value="0" name="dstate_update" checked> 启用
										</label>
										<label>
											<input type="radio" value="1" name="dstate_update"> 禁用
										</label>
									</div>
								</div>
							</div>
							<div class="form-group">
								<div class="col-sm-offset-1 col-sm-10">
									<div class="checkbox">
										<label>
											<span style="color: red;"></span>
										</label>
										
									</div>
								</div>
							</div>
						</form>
					</div>
					<input type="hidden" name="" value="" id="version">
					<input type="hidden" name="" value="" id="uid">
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						<button type="button" class="btn btn-primary" onclick="updateDictDo()">保存</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- 授权的Modal -->
		<div class="modal fade" id="priModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
		  <div class="modal-dialog" role="document">
		    <div class="modal-content">
		      <div class="modal-header">
		        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
		        <h4 class="modal-title" id="myModalLabel">选择角色</h4>
		      </div>
		      <div class="modal-body">
		        <form class="form-horizontal">
		          <div class="form-group">
					  <input type="hidden" id="eid" value=""/>
		            <label for="inputEmail3" class="col-sm-2 control-label">角色</label>
		            <div class="col-sm-10">
		              <select class="form-control" id="selectRoles">
						  <!-- <option value="1">医生</option> -->
					  </select>
		            </div>
		          </div>
		        </form>
		      </div>
		      <div class="modal-footer">
		        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
		        <button type="button" class="btn btn-primary" onclick="priDo()">保存授权</button>
		      </div>
		    </div>
		  </div>
		</div>
	</body>
</html